<template>
    <div class="app-container">

        <!-- 顶部搜索栏 -->
        <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
            <el-form-item label="证件类型" prop="type">
                <el-input v-model="queryParams.type" placeholder="请输入证件类型" style="width: 140px;" clearable
                    @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="证件编号" prop="number">
                <el-input v-model="queryParams.number" placeholder="请输入证件编号" style="width: 150px;" clearable
                    @keyup.enter="handleQuery" />
            </el-form-item>

            <el-form-item label="创建日期" prop="creationDate">
                <el-date-picker clearable v-model="queryParams.creationDate" style="width: 150px;" type="date"
                    value-format="YYYY-MM-DD" placeholder="请选择创建日期">
                </el-date-picker>
            </el-form-item>

            <el-form-item label="有效日期" prop="effectiveDate">
                <el-date-picker clearable v-model="queryParams.effectiveDate" type="date" style="width: 170px;"
                    value-format="YYYY-MM-DD" placeholder="请选择证件有效日期">
                </el-date-picker>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <!-- 功能按钮 -->
        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="primary" plain icon="Plus" @click="handleAdd"
                    v-hasPermi="['personal:information:add']">新增</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
                    v-hasPermi="['personal:information:edit']">修改</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
                    v-hasPermi="['personal:information:remove']">删除</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="warning" plain icon="Download" @click="handleExport"
                    v-hasPermi="['personal:information:export']">导出</el-button>
            </el-col>
            <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <!-- 表格主体 -->
        <el-table v-loading="loading" :data="informationList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <!-- <el-table-column label="主键，唯一标识符" align="center" prop="id" /> -->
            <el-table-column label="证件类型" align="center" prop="type" width="80" />
            <el-table-column label="创建日期" align="center" prop="creationDate" width="100">
                <template #default="scope">
                    <span>{{ parseTime(scope.row.creationDate, '{y}-{m}-{d}') }}</span>
                </template>
            </el-table-column>
            <el-table-column label="备注" align="center" prop="notes" />
            <el-table-column label="有效日期" align="center" prop="effectiveDate" width="100">
                <template #default="scope">
                    <span>{{ parseTime(scope.row.effectiveDate, '{y}-{m}-{d}') }}</span>
                </template>
            </el-table-column>

            <el-table-column label="照片" align="center" prop="photo">
                <template #default="scope">

                    <div>
                        <img v-if="scope.row.photo.length && scope.row.photo[0]?.url" :src="scope.row.photo[0].url"
                            alt="照片" style="width: 50px; height: auto;" />
                        <span style="color: red;" v-else>暂无上传</span>
                    </div>
                    <!-- <img :src="scope.row.photo[0]?.url" alt="照片" style="width: 50px; height: auto;" /> -->
                </template>
            </el-table-column>
            <el-table-column label="证件编号" align="center" prop="number" />
            <el-table-column label="往返次数" align="center" prop="roundTripFrequency" />
            <el-table-column label="证件时效" align="center" prop="ageing" />
            <el-table-column label="保管机构" align="center" prop="custodian" />
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template #default="scope">
                    <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                        v-hasPermi="['personal:information:edit']">修改</el-button>
                    <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                        v-hasPermi="['personal:information:remove']">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize" @pagination="getList" />

        <!-- 添加或修改证件信息，用于存储证件的详细信息对话框 -->
        <el-dialog :title="title" v-model="open" width="500px" append-to-body>
            <el-form ref="informationRef" :model="form" :rules="rules" label-width="80px">
                <el-form-item label="类型" prop="type">
                    <el-input v-model="form.type" placeholder="请输证件类型" />
                </el-form-item>
                <el-form-item label="证件编号" prop="number">
                    <el-input v-model="form.number" placeholder="请输入证件编号" />
                </el-form-item>
                <div style="display: flex;">
                    <el-form-item label="创建日期" prop="creationDate">
                        <el-date-picker clearable v-model="form.creationDate" style="width: 140px;" type="date"
                            value-format="YYYY-MM-DD" placeholder="请选择创建日期">
                        </el-date-picker>
                    </el-form-item>
                    <div style="width: 40px;"></div>
                    <el-form-item label="有效日期" prop="effectiveDate">
                        <el-date-picker clearable v-model="form.effectiveDate" style="width: 140px;" type="date"
                            value-format="YYYY-MM-DD" placeholder="请选择证件有效日期">
                        </el-date-picker>
                    </el-form-item>

                </div>



                <div style="display: flex;">
                    <el-form-item label="往返次数" prop="roundTripFrequency">
                        <el-input v-model="form.roundTripFrequency" style="width: 140px;" placeholder="请输入往返次数" />
                    </el-form-item>
                    <div style="width: 40px;"></div>
                    <el-form-item label="证件时效" prop="ageing">
                        <el-input v-model="form.ageing" style="width: 140px;" placeholder="请输入证件时效" />
                    </el-form-item>
                </div>
                <el-form-item label="保管机构" prop="custodian">
                    <el-input v-model="form.custodian" placeholder="请输入保管机构" />
                </el-form-item>


                <!-- <el-form-item label="证件照片" prop="photo">
                    <el-upload v-model:file-list="fileList" list-type="picture-card"
                        :on-preview="handlePictureCardPreview" :on-remove="handleRemove">
                        <el-icon>
                            <Plus />
                        </el-icon>
                    </el-upload>

                    <el-dialog v-model="dialogVisible">
                        <img w-full :src="dialogImageUrl" alt="Preview Image" />
                    </el-dialog>
                </el-form-item> -->




                <!-- <el-form-item label="证件图片">
                    <el-upload class="dl-avatar-uploader-min square"
                        :class="{ uploadBtn: showBtnDealImg, disUploadBtn: noneBtnImg }" :http-request="handleUpload"
                        :limit="limitCountImg" :on-success="coverFileSuccess" :on-remove="coverFileRemove"
                        :on-exceed="handleExceedCover" :before-upload="beforeImageUpload" :on-change="handleImgChange"
                        :file-list="fileList" list-type="picture-card" accept="image/*" multiple>
                        <el-button type="text">上传图片</el-button>
                        <template #tip>
                            <div class="el-upload__tip">最多上传9张图片,且单张图片大小不能超过10MB</div>
                        </template>
                    </el-upload>
                </el-form-item> -->
                <el-form-item label="证件图片">
                    <el-upload class="dl-avatar-uploader-min square"
                        :class="{ uploadBtn: showBtnDealImg, disUploadBtn: noneBtnImg }" :http-request="handleUpload"
                        :limit="limitCountImg" :on-success="coverFileSuccess" :on-remove="coverFileRemove"
                        :on-exceed="handleExceedCover" :before-upload="beforeImageUpload" :on-change="handleImgChange"
                        :file-list="fileList" list-type="picture-card" accept="image/*" multiple
                        :disabled="fileList.length >= limitCountImg" 
                        >
                        <template v-if="fileList.length < limitCountImg">
                            <el-button type="text">上传图片</el-button>
                        </template>
                        <template v-else>
                            <div>已达到上传上限</div>
                        </template>
                        <template #tip>
                            <div class="el-upload__tip">最多上传 {{ limitCountImg }}张图片,且单张图片大小不能超过10MB</div>
                        </template>
                    </el-upload>
                </el-form-item>






                <el-form-item label="备注" prop="notes">
                    <el-input v-model="form.notes" style="width: 100%" :autosize="{ minRows: 2, maxRows: 4 }"
                        type="textarea" placeholder="请输入证件备注信息" />
                </el-form-item>


            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitForm">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup name="Information">
import { listInformation, getInformation, delInformation, addInformation, updateInformation } from "@/api/personal/information";
import { addImg } from "@/api/personal/fileupload";
import { Plus } from '@element-plus/icons-vue'
//import { UploadProps, UploadUserFile } from 'element-plus'
const { proxy } = getCurrentInstance();
import { nextTick } from 'vue';

const informationList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
    form: {},
    queryParams: {
        pageNum: 1,
        pageSize: 10,
        creationDate: null,
        notes: null,
        effectiveDate: null,
        type: null,
        photo: null,
        number: null,
        roundTripFrequency: null,
        ageing: null,
        custodian: null
    },
    rules: {
        creationDate: [
            { required: true, message: "创建日期不能为空", trigger: "blur" }
        ],
        effectiveDate: [
            { required: true, message: "证件有效日期不能为空", trigger: "blur" }
        ],
        type: [
            { required: true, message: "证件类型不能为空", trigger: "change" }
        ],
        photo: [
            { required: true, message: "照片不能为空", trigger: "blur" }
        ],
        number: [
            { required: true, message: "证件编号不能为空", trigger: "blur" }
        ],
        ageing: [
            { required: true, message: "证件时效不能为空", trigger: "blur" }
        ],
    }
});

const { queryParams, form, rules } = toRefs(data);


//图片上传的js
// 假设这些是从你的Vue 3组件的props、data或computed中获取的  
const showBtnDealImg = ref(true);
const noneBtnImg = ref(false);
const limitCountImg = ref(3);
const fileList = ref([]);


// 自定义上传方法  
function handleUpload(file) {
    addImg(file)
        .then(response => {
            fileList.value = [...fileList.value, { url: response.data.url, status: 'success' }];
        })
        .catch(error => {
            // 处理错误逻辑  
        });
}

// 文件上传成功调用
function coverFileSuccess(response, file, fileList) {
    console.log('File uploaded successfully:', response);
    console.log('File list:', fileList.value);
    // 更新UI或执行其他操作  
}


/**
 * 处理文件移除操作
 * 
 * 当用户从文件列表中移除一个文件时，此函数将被调用
 * 它的作用是通知开发者文件已被移除，并且可以在该函数中
 * 执行一些后续操作，比如更新文件列表或清理相关资源
 * 
 * @param {Object} file - 被移除的文件对象，包含文件的相关信息
 * @param {Array} fileList - 当前文件列表，包含所有已上传或待上传的文件
 */
function coverFileRemove(file, fileList) {
    console.log('File removed:', file);
    console.log('File removed:', fileList);
    // 更新fileList或执行其他操作  
}

function handleExceedCover(files, fileList) {
    this.$message.warning(`当前限制选择 ${limitCountImg.value} 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
}

//文件上传之前得动作 校验文件大小
function beforeImageUpload(file) {
    const isJPGorPNG = file.type === 'image/jpeg' || file.type === 'image/png';
    const isLt10M = file.size / 1024 / 1024 < 10;

    if (!isJPGorPNG) {
        this.$message.error('上传头像图片只能是 JPG/PNG 格式!');
        return false;
    }
    if (!isLt10M) {
        this.$message.error('上传头像图片大小不能超过 10MB!');
        return false;
    }
    return true;
}

// 更新fileList或执行其他操作
function handleImgChange(file, fileList) {
    console.log('File list changed:', fileList);
      
}






/** 查询证件信息，用于存储证件的详细信息列表 */
function getList() {
    loading.value = true;
    listInformation(queryParams.value).then(response => {
        informationList.value = response.rows.map(item => ({
            ...item,
            photo: JSON.parse(item.photo),
        }));
        total.value = response.total;
        loading.value = false;
    });
}

// 取消按钮
function cancel() {
    open.value = false;
    reset();
}

// 表单重置
function reset() {
    form.value = {
        id: null,
        creationDate: null,
        notes: null,
        effectiveDate: null,
        type: null,
        photo: null,
        number: null,
        roundTripFrequency: null,
        ageing: null,
        custodian: null
    };
    proxy.resetForm("informationRef");
}

/** 搜索按钮操作 */
function handleQuery() {
    queryParams.value.pageNum = 1;
    getList();
}

/** 重置按钮操作 */
function resetQuery() {
    proxy.resetForm("queryRef");
    handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
    ids.value = selection.map(item => item.id);
    single.value = selection.length != 1;
    multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
    reset();
    open.value = true;
    title.value = "添加证件信息，用于存储证件的详细信息";
}

/** 修改按钮操作 */
function handleUpdate(row) {
    reset();
    const _id = row.id || ids.value
    getInformation(_id).then(response => {
        console.log("修改按钮--------*********---------")
        console.log("获取的图片URL：", response.data.photo);

        form.value = response.data;
        //fileList.value.push(response.data.photo);  
        if (response.data.photo != null && response.data.photo.trim() !== '') {
            fileList.value = JSON.parse(response.data.photo);
        }

        //把数据库里的图片链接 回显到页面上
        //fileList.value.push({ url: response.data.photo, status: 'success' });
        //JSON.parse(response.data.photo); 

        nextTick(() => {
            console.log("更新后的fileList：", fileList.value);
        });


        open.value = true;
        title.value = "修改证件信息，用于存储证件的详细信息";
    });
}

/** 提交按钮 */
function submitForm() {
    proxy.$refs["informationRef"].validate(valid => {
        console.log(valid);
        if (valid) {
            console.log("修改方法");
            if (form.value.id != null) {
                console.log(fileList.value)
                //添加url链接
                form.value.photo = JSON.stringify(fileList.value);
                console.log(form.value)
                updateInformation(form.value).then(response => {
                    proxy.$modal.msgSuccess("修改成功");
                    open.value = false;
                    getList();
                });
            } else {
                console.log("新增方法");
                addInformation(form.value).then(response => {
                    proxy.$modal.msgSuccess("新增成功");
                    open.value = false;
                    getList();
                });
            }
        }
    });
}

/** 删除按钮操作 */
function handleDelete(row) {
    const _ids = row.id || ids.value;
    proxy.$modal.confirm('是否确认删除证件信息，用于存储证件的详细信息编号为"' + _ids + '"的数据项？').then(function () {
        return delInformation(_ids);
    }).then(() => {
        getList();
        proxy.$modal.msgSuccess("删除成功");
    }).catch(() => { });
}

/** 导出按钮操作 */
function handleExport() {
    proxy.download('personal/information/export', {
        ...queryParams.value
    }, `information_${new Date().getTime()}.xlsx`)
}

getList();
</script>

<style scoped>
.app-container {
    height: 85vh;
    margin: 10px;
    box-shadow: 2px 2px 3px 3px rgba(167, 167, 167, 0.5);
}
</style>
